package com.imay.photopicker.view;


import android.animation.ObjectAnimator;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.support.annotation.ColorInt;
import android.support.annotation.DrawableRes;
import android.support.annotation.StringRes;
import android.support.v7.widget.LinearLayoutCompat;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.imay.capturefilter.R;
import com.imay.photopicker.util.RecyclerViewUtil;

public class TitleBar extends LinearLayout implements View.OnClickListener {
    private LinearLayout mRootView; //增加rootView适应沉浸状态栏
    private LinearLayout mLeftView;
    private LinearLayout mMiddleView;
    private LinearLayout mRightView;

    private TextView mTitleTextView;
    private ImageView mLeftImageView;
    private ImageView mRightImageView;

    private int mTitleTextSize = 14;   //文字大小
    private int mTitleColor = Color.WHITE;

    private boolean mTitleFixedCenter = true;  //标题是否居中

    /**
     * 双击滑动到顶部的参数
     */
    private static final long DOUBLE_CLICK_TIME_DELTA = 300;//milliseconds
    private long lastClickTime = 0;
    private View mSmoothToTopView;

    public TitleBar(Context context) {
        super(context);
        init(context);
    }

    public TitleBar(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public TitleBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public TitleBar(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context);
    }

    private void init(Context context) {
        mRootView = new LinearLayout(context);

        mRootView.setGravity(Gravity.CENTER);
        mRootView.setOrientation(HORIZONTAL);


        mLeftView = new LinearLayout(context);
        mLeftView.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        mLeftView.setGravity(Gravity.CENTER_HORIZONTAL);

        mMiddleView = new LinearLayout(context);
        mMiddleView.setLayoutParams(new LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1));
        mMiddleView.setGravity(Gravity.CENTER);

        mRightView = new LinearLayout(context);
        mRightView.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        mRightView.setGravity(Gravity.CENTER_HORIZONTAL);

        mTitleTextView = createTextView();
        mTitleTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, mTitleTextSize);
        mTitleTextView.setTextColor(mTitleColor);
        mMiddleView.addView(mTitleTextView, 0);

        mMiddleView.setOnClickListener(this);

        mRootView.addView(mLeftView);
        mRootView.addView(mMiddleView);
        mRootView.addView(mRightView);

        addView(mRootView, new LinearLayoutCompat.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, getResources().getDimensionPixelOffset(R.dimen.title_bar_height)));
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        updateTitleContainer();
    }

    //中间文字偏移一定位置保证居中
    private void updateTitleContainer() {
        int leftPadding;
        int rightPadding;
        if (mTitleFixedCenter) {
            if (mLeftView.getWidth() >= mRightView.getWidth()) {
                leftPadding = 0;
                rightPadding = mLeftView.getWidth() - mRightView.getWidth();
            } else {
                leftPadding = mRightView.getWidth() - mLeftImageView.getWidth();
                rightPadding = 0;
            }
        } else {
            leftPadding = 0;
            rightPadding = 0;
        }
        if (leftPadding != mMiddleView.getPaddingLeft() || rightPadding != mMiddleView.getPaddingRight()) {
            mMiddleView.setPadding(leftPadding, 0, rightPadding, 0);
        }
    }

    private ImageView createImageView() {
        ImageView imageView = new ImageView(getContext());
        imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
        int padding = (int) getResources().getDimension(R.dimen.image_button_padding);
        imageView.setPadding(padding, padding, padding, padding); //统一增加12个像素
        return imageView;
    }

    private TextView createTextView() {
        TextView textView = new TextView(getContext());
        textView.setGravity(Gravity.CENTER);
//        textView.setTextColor(mTextColor);  //默认和标题栏相同的颜色
        return textView;
    }

    public void setTitle(CharSequence text) {
        mTitleTextView.setText(text);
    }

    public void setTitle(@StringRes int resId) {
        setTitle(getResources().getString(resId));
    }

    public void setTitleSize(int size) {
        mTitleTextSize = size;
        mTitleTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, mTitleTextSize);
    }

    public void setTitleColor(@ColorInt int color) {
        mTitleColor = color;
        mTitleTextView.setTextColor(color);
    }

    public void setLeftImageResource(@DrawableRes int resId) {
        if (mLeftImageView == null) {
            mLeftImageView = createImageView();
            mLeftView.addView(mLeftImageView);
            mLeftView.setVisibility(VISIBLE);
        }
        mLeftImageView.setImageResource(resId);
    }

    public void setRightImageResource(@DrawableRes int resId) {
        if (mRightImageView == null) {
            mRightImageView = createImageView();
            mRightView.addView(mRightImageView);
            mRightView.setVisibility(VISIBLE);
        }
        mRightImageView.setImageResource(resId);
    }

    public void setLeftImageOnClickListener(OnClickListener onClickListener) {
        mLeftImageView.setOnClickListener(onClickListener);
    }

    public void setRightImageOnClickListener(OnClickListener onClickListener) {
        mRightImageView.setOnClickListener(onClickListener);
    }

    public ViewGroup getLeftView() {
        return mLeftView;
    }

    public ViewGroup getMiddleView() {
        return  mMiddleView;
    }

    public ViewGroup getRightView() {
        return mRightView;
    }

    /**
     * 双击操作，目前只对WebView,ScrollView,AbsListView做操作
     */
    private void doubleClick() {
        if (mSmoothToTopView != null) {
            if (mSmoothToTopView instanceof AbsListView) {
                AbsListView smoothToTopView = (AbsListView) mSmoothToTopView;
                int firstVisiblePosition = smoothToTopView.getFirstVisiblePosition();
                if (firstVisiblePosition < 11) {
                    smoothToTopView.smoothScrollToPosition(0);
                } else {
                    //太多item时加快速度
                    smoothToTopView.setSelection(10);
                    smoothToTopView.smoothScrollToPosition(0);
                }
                smoothToTopView.clearFocus();
            } else if (mSmoothToTopView instanceof RecyclerView) {
                RecyclerView smoothToTopView = (RecyclerView) mSmoothToTopView;
                int firstVisiblePosition = RecyclerViewUtil.getRecyclerFirstVisibleItemPosition(smoothToTopView);
                if (firstVisiblePosition < 11) {
                    smoothToTopView.smoothScrollToPosition(0);
                } else {
                    //太多item时加快速度
                    smoothToTopView.scrollToPosition(10);
                    smoothToTopView.smoothScrollToPosition(0);
                }
                smoothToTopView.clearFocus();
            } else if (mSmoothToTopView instanceof ScrollView) {
                ScrollView scrollView = ((ScrollView) mSmoothToTopView);
                scrollView.smoothScrollTo(scrollView.getScrollX(), 0);
            } else if (mSmoothToTopView instanceof WebView) {
                ObjectAnimator anim = ObjectAnimator.ofInt(mSmoothToTopView, "scrollY",
                        mSmoothToTopView.getScrollY(), 0);
                anim.setDuration(200).start();
            }
        }
    }

    /**
     * 设置可滑动的View
     *
     * @param smoothToTopView
     */
    public void setSmoothToTopView(View smoothToTopView) {
        mSmoothToTopView = smoothToTopView;
    }

    @Override
    public void onClick(View v) {
        long clickTime = System.currentTimeMillis();
        if (clickTime - lastClickTime < DOUBLE_CLICK_TIME_DELTA) {
            /**双击在一定间隔之内触发方法**/
            doubleClick();
            lastClickTime = 0;
        } else {
            lastClickTime = clickTime;
        }
    }
}
